"use strict";
var login = function () {

    function eventHandler() {
        $(document).off('mouseover', '.show-qr-code');
        $(document).on('mouseover', '.show-qr-code', function () {
            $(this).siblings().collapse('show');
        });
        $(document).off('mouseleave', '.show-qr-code');
        $(document).on('mouseleave', '.show-qr-code', function () {
            $(this).siblings().collapse('hide');
        });
    }

    function saveStorage($form) {
        var username = $form.find('[name="username"]').val();
        var password = $form.find('[name="password"]').val();
        if ($form.find('[name="rememberPassword"]').prop('checked')) {
            //存储到loaclStage
            localStorage.setItem("username", username);
            localStorage.setItem("password", password);
        } else {
            localStorage.removeItem("username");
            localStorage.removeItem("password");
        }
    }

    /**
     * 验证表单
     * @param $form
     */
    function validateForm($form) {
        $form.validate({
            rules: {
                username: {
                    required: true,
                    minlength: 4
                },
                password: {
                    required: true,
                    minlength: 4
                }
            },
            messages: {
                username: {
                    required: "请输入用户名!",
                    minlength: "用户名必须至少4个字符!"
                },
                password: {
                    required: "请输入密码!",
                    minlength: "密码至少需要4个字符!"
                }
            },
            //display error alert on form submit
            invalidHandler: function(event, validator) {
                if (validator.errorList.length > 0) {
                    $(validator.errorList[0].element).focus();
                }
            },
            submitHandler: function(form) {
                saveStorage($(form));
                location.href = '/default/';
            }
        });
    }

    /**
     * 填充表单
     * @param $form
     */
    function fillForm($form) {
        var username = localStorage.getItem('username');
        var password = localStorage.getItem('password');
        if (username && password) {
            $form.find('[name="username"]').val(username);
            $form.find('[name="password"]').val(password);
            $form.find('[name="rememberPassword"]').prop('checked', true);
        } else {
            $form.find('[name="rememberPassword"]').prop('checked', false);
        }

    }

    return {
        init: function() {
            eventHandler();
            var $form = $('#login-form');
            fillForm($form);
            validateForm($form);
        }
    };
}();

jQuery(document).ready(function () {
    login.init();
});